﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI;

namespace Jy123.BLL.Race
{
    public class Race
    {
        public class ClubRank
        {
            private int _id;
            private int _value;
            private string _clubName;
            private int _cost;
            private int _prelium;
            public int ID
            {
                set { _id = value; }
                get { return _id; }
            }
            public int ClubValue
            {
                set { _value = value; }
                get { return _value; }
            }
            public int Cost
            {
                set { _cost = value; }
                get { return _cost; }
            }
            public int Prelium
            {
                set { _prelium = value; }
                get { return _prelium; }
            }
            public string ClubName
            {
                set { _clubName = value; }
                get { return _clubName; }
            }
        }

        public class CompareClub : IComparer
        {
            int IComparer.Compare(object a, object b)
            {
                ClubRank c1 = (ClubRank)a;
                ClubRank c2 = (ClubRank)b;

                if (c1.ClubValue < c2.ClubValue)
                    return 1;

                if (c1.ClubValue > c2.ClubValue)
                    return -1;

                else
                    return 0;
            }
        }
        /// <summary>
        /// 赛场选中两个俱乐部开始比赛
        /// </summary>
        /// <param name="venues">加入的赛场</param>
        /// <param name="club1">俱乐部1</param>
        /// <param name="club2">俱乐部2</param>
        public void StartRace(Model.Venues_Main venues, Model.Club_Main club1, Model.Club_Main club2)
        {
            string strRaceClub = venues.RaceClub;
            Public_Game BLLGame = new Public_Game();
            Venues_Main BLLVenues = new Venues_Main();
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            User_Main BLLUser = new User_Main();
            Public_Level BLLLevel = new Public_Level();
            Model.Public_Level level = BLLLevel.GetModel(venues.FLevel.Value);
            Model.User_Main user1 = BLLUser.GetModel(club1.FUser.Value);
            Model.User_Main user2 = BLLUser.GetModel(club2.FUser.Value);
            Model.User_Main vUser = BLLUser.GetModel(venues.FUser.Value);
            Model.Module_Main module1 = BLLModule.GetModel(club1.ID);
            Model.Module_Main module2 = BLLModule.GetModel(club2.ID);
            Model.Module_Main vModule = BLLModule.GetModel(venues.ID);
            //扣除参赛费用
            decimal cost = 0;
            if (level.Cost.HasValue)
            {
                cost = level.Cost.Value;
            }
            user1.Cash = Convert.ToInt32(user1.Cash.Value - cost);
            user2.Cash = Convert.ToInt32(user2.Cash.Value - cost);
            BLLUser.Update(user1);
            BLLUser.Update(user2);
            club1.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
            club2.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
            module1.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
            module2.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);//设置俱乐部为比赛状态

            BLLClub.Update(club1);
            BLLModule.Update(module1);
            BLLClub.Update(club2);
            BLLModule.Update(module2);
            venues.RaceClub = club1.ID.ToString() + "," + club2.ID.ToString();
            venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Race);//赛场状态设置为比赛
            vModule.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Race);

            string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
            List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
            if (listGame.Count > 0)
            {
                Model.Public_Game game = listGame[0];
                game.IsEnd = false;
                game.RaceTime = DateTime.Now;
                game.FVenues = venues.ID;
                game.VenuesName = venues.VName;
                BLLGame.Update(game);
            }
            else
            {
                Model.Public_Game game = new Jy123.Model.Public_Game();
                game.IsEnd = false;
                game.RaceTime = DateTime.Now;
                game.FVenues = venues.ID;
                game.VenuesName = venues.VName;
                BLLGame.Add(game);
            }
            BLLVenues.Update(venues);
            BLLModule.Update(vModule);
        }

        /// <summary>
        /// 赛车赛场选中俱乐部开始比赛
        /// </summary>
        /// <param name="venues">加入的赛场</param>        
        public void StartRace(Model.Venues_Main venues)
        {
            string strRaceClub = venues.RaceClub;
            string strForSQL = strRaceClub.Replace("_", ",");

            Public_Game BLLGame = new Public_Game();
            Venues_Main BLLVenues = new Venues_Main();
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            User_Main BLLUser = new User_Main();
            Public_Level BLLLevel = new Public_Level();
            Model.Public_Level level = BLLLevel.GetModel(venues.FLevel.Value);
            List<Model.Club_Main> listClub = BLLClub.GetModelList("ID IN (" + strForSQL + ")");
            Model.User_Main vUser = BLLUser.GetModel(venues.FUser.Value);
            List<Model.Module_Main> listModule = BLLModule.GetModelList("ID IN (" + strForSQL + ")");
            List<Model.User_Main> listFriend = BLLUser.GetModelList("ID IN (SELECT FUser FROM Club_Main WHERE ID IN (" + strForSQL + "))");
            Model.Module_Main vModule = BLLModule.GetModel(venues.ID);
            //扣除参赛费用
            decimal cost = 0;
            if (level.Cost.HasValue)
            {
                cost = level.Cost.Value;
            }
            vUser.Cash = Convert.ToInt32(vUser.Cash.Value + cost * listFriend.Count);
            BLLUser.Update(vUser);
            foreach (Model.User_Main user in listFriend)
            {
                user.Cash = Convert.ToInt32(user.Cash.Value - cost);
                BLLUser.Update(user);
            }
            foreach (Model.Club_Main club in listClub)
            {
                club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);

                BLLClub.Update(club);
            }
            foreach (Model.Module_Main module in listModule)
            {
                module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);          //设置俱乐部为比赛状态            
                BLLModule.Update(module);
            }
            venues.RaceClub = strForSQL;
            venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Race);//赛场状态设置为比赛
            vModule.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Race);
            string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
            List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
            if (listGame.Count > 0)
            {
                Model.Public_Game game = listGame[0];
                game.IsEnd = false;
                game.RaceTime = DateTime.Now;
                game.FVenues = venues.ID;
                game.VenuesName = venues.VName;
                BLLGame.Update(game);
            }
            else
            {
                Model.Public_Game game = new Jy123.Model.Public_Game();
                game.IsEnd = false;
                game.RaceTime = DateTime.Now;
                game.FVenues = venues.ID;
                game.VenuesName = venues.VName;
                BLLGame.Add(game);
            }

            BLLVenues.Update(venues);
            BLLModule.Update(vModule);
        }

        /// <summary>
        /// 俱乐部加入赛场，如果赛场为空状态那么开始等待，如果赛场为等待状态那么开始比赛
        /// </summary>
        /// <param name="venues">加入的赛场</param>
        /// <param name="club">俱乐部</param>
        public void JoinVenues(Model.Venues_Main venues, Model.Club_Main club)
        {
            string strRaceClub = venues.RaceClub;
            Public_Game BLLGame = new Public_Game();
            Venues_Main BLLVenues = new Venues_Main();
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            User_Main BLLUser = new User_Main();
            Public_Level BLLLevel = new Public_Level();
            Model.Public_Level level = BLLLevel.GetModel(venues.FLevel.Value);
            Model.Module_Main module = BLLModule.GetModel(club.ID);
            Model.Module_Main vModule = BLLModule.GetModel(venues.ID);
            int clubId = club.ID;
            if (!string.IsNullOrEmpty(strRaceClub))
            {
                string[] strClubList = strRaceClub.Replace("_", ",").Split(',');
                if (!IsInList(strClubList, clubId))
                {
                    string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
                    List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
                    if (listGame.Count > 0)
                    {
                        Model.Public_Game game = listGame[0];
                        game.IsEnd = false;
                        game.RaceTime = DateTime.Now;
                        game.FVenues = venues.ID;
                        game.VenuesName = venues.VName;
                        BLLGame.Update(game);
                        int clubId1 = int.Parse(strRaceClub);
                        Model.Club_Main club1 = BLLClub.GetModel(clubId1);
                        Model.Module_Main module1 = BLLModule.GetModel(clubId1);
                        club1.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
                        module1.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
                        BLLClub.Update(club1);
                        BLLModule.Update(module1);
                        club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
                        module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Race);
                        BLLClub.Update(club);
                        BLLModule.Update(module);
                        Model.User_Main user1 = BLLUser.GetModel(club1.FUser.Value);
                        Model.User_Main user2 = BLLUser.GetModel(club.FUser.Value);
                        //扣除参赛费用
                        decimal cost = 0;
                        if (level.Cost.HasValue)
                        {
                            cost = level.Cost.Value;
                        }
                        user1.Cash = Convert.ToInt32(user1.Cash.Value - cost);
                        user2.Cash = Convert.ToInt32(user2.Cash.Value - cost);
                        BLLUser.Update(user1);
                        BLLUser.Update(user2);
                        vModule.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Race);
                        BLLModule.Update(vModule);
                        venues.RaceClub = strRaceClub + "," + club.ID.ToString();
                        venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Race);//赛场状态设置为比赛
                        BLLVenues.Update(venues);
                    }
                }
            }
            else
            {
                club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Wait);
                module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Wait);
                BLLClub.Update(club);
                BLLModule.Update(module);
                Model.Public_Game game = new Jy123.Model.Public_Game();
                game.IsEnd = false;
                game.FVenues = venues.ID;
                game.VenuesName = venues.VName;
                game.RaceTime = DateTime.Now;
                BLLGame.Add(game);
                venues.RaceClub = club.ID.ToString();
                venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Wait);//赛场状态设置为等待
                vModule.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Wait);
                BLLModule.Update(vModule);
                BLLVenues.Update(venues);
            }
        }

        private bool IsInList(string[] strList, int id)
        {
            for (int i = 0; i < strList.Length; i++)
            {
                if (strList[i].Equals(id.ToString()))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 俱乐部退出赛场
        /// </summary>
        /// <param name="venues">赛场</param>
        public void QuitVenues(Model.Venues_Main venues)
        {
            Public_Game BLLGame = new Public_Game();
            Venues_Main BLLVenues = new Venues_Main();
            string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
            List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
            if (listGame.Count > 0)
            {
                Jy123.Model.Public_Game game = listGame[0];
                BLLGame.Delete(game.ID);
            }
            int clubId = int.Parse(venues.RaceClub);
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            Model.Club_Main club = BLLClub.GetModel(clubId);
            Model.Module_Main cModule = BLLModule.GetModel(clubId);
            Model.Module_Main vModule = BLLModule.GetModel(venues.ID);
            club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
            cModule.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
            vModule.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Empty);
            venues.RaceClub = string.Empty;
            venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Empty);
            BLLVenues.Update(venues);
            BLLClub.Update(club);
            BLLModule.Update(cModule);
            BLLModule.Update(vModule);
        }

        /// <summary>
        /// 计算比赛结果，派发奖金，保存比赛记录
        /// </summary>
        /// <param name="venues">进行比赛的场地</param>
        /// <returns></returns>
        public ArrayList EndRace(Model.Venues_Main venues)
        {
            ArrayList arrayList = new ArrayList();
            User_Main BLLUser = new User_Main();
            Public_Game BLLGame = new Public_Game();
            Venues_Main BLLVenues = new Venues_Main();
            Club_Game BLLClubGame = new Club_Game();
            Club_Main BLLClub = new Club_Main();
            Public_Level BLLLevel = new Public_Level();
            Module_Main BLLModule = new Module_Main();
            string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
            List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
            if (listGame.Count > 0)
            {
                Model.Public_Level vLevel = BLLLevel.GetModel(venues.FLevel.Value);
                string[] strClubId = venues.RaceClub.Split(',');
                Model.Club_Main club1 = BLLClub.GetModel(int.Parse(strClubId[0]));
                Model.Club_Main club2 = BLLClub.GetModel(int.Parse(strClubId[1]));
                Model.Public_Level cLevel1 = BLLLevel.GetModel(club1.FLevel.Value);
                Model.Public_Level cLevel2 = BLLLevel.GetModel(club2.FLevel.Value);
                Model.Public_Game game = listGame[0];
                Model.User_Main user1 = BLLUser.GetModel(club1.FUser.Value);
                Model.User_Main user2 = BLLUser.GetModel(club2.FUser.Value);
                Model.User_Main userV = BLLUser.GetModel(venues.FUser.Value);
                Model.Module_Main cM1 = BLLModule.GetModel(club1.ID);
                Model.Module_Main cM2 = BLLModule.GetModel(club2.ID);
                Model.Module_Main vM = BLLModule.GetModel(venues.ID);

                //产生比赛结果，生成比赛结果记录
                decimal premium = 0;
                if (vLevel.Premium.HasValue)
                {
                    premium = vLevel.Premium.Value;
                }
                Model.Club_Game cGame1 = new Jy123.Model.Club_Game();
                Model.Club_Game cGame2 = new Jy123.Model.Club_Game();
                cGame1.FVenues = venues.ID;
                cGame1.FClub = club1.ID;
                cGame1.ClubName = club1.CName;
                cGame1.FGame = game.ID;
                cGame2.FVenues = venues.ID;
                cGame2.FClub = club2.ID;
                cGame2.ClubName = club2.CName;
                cGame2.FGame = game.ID;
                int clubValue1 = Calculate(cLevel1, club1);
                int clubValue2 = Calculate(cLevel2, club2);
                if (clubValue1 == 0)
                {
                    clubValue1 = 1;
                }
                if (clubValue2 == 0)
                {
                    clubValue2 = 1;
                }
                if (clubValue1 < 0 && clubValue2 < 0)
                {
                    if (clubValue1 <= clubValue2)
                    {
                        clubValue1 = clubValue1 + clubValue2;
                        clubValue2 = clubValue1 - clubValue2;
                        clubValue1 = clubValue1 - clubValue2;
                    }
                    else
                    {
                        clubValue2 = clubValue1 + clubValue2;
                        clubValue1 = clubValue2 - clubValue1;
                        clubValue2 = clubValue2 - clubValue1;
                    }
                    clubValue1 = (-1) * clubValue1;
                    clubValue2 = (-1) * clubValue2;
                }
                else if (clubValue1 < 0 && clubValue2 > 0)
                {
                    int temp = -1 * clubValue1;
                    if (temp <= clubValue2)
                    {
                        clubValue1 = temp;
                        clubValue2 = clubValue2 + temp;
                    }
                    else
                    {
                        clubValue1 = clubValue2;
                        clubValue2 = temp;
                    }
                }
                else if (clubValue1 > 0 && clubValue2 < 0)
                {
                    int temp = -1 * clubValue2;
                    if (temp <= clubValue1)
                    {
                        clubValue2 = temp;
                        clubValue1 = clubValue1 + temp;
                    }
                    else
                    {
                        clubValue2 = clubValue1;
                        clubValue1 = temp;
                    }
                }
                int allValue = clubValue1 + clubValue2;
                if (allValue > 0)
                {
                    int proportion;
                    bool isClub1Lose = clubValue1 < clubValue2;
                    if (isClub1Lose)
                    {
                        proportion = clubValue1 * 10 / allValue;
                    }
                    else
                    {
                        proportion = clubValue2 * 10 / allValue;
                    }
                    if (proportion < 1)
                    {
                        proportion = 1;
                    }
                    Random random = new Random();
                    int bigScore = 0;
                    int smallScore = 0;
                    string strResult = "";
                    switch (proportion)
                    {
                        case 1:
                        case 2:
                        case 3:
                            bigScore = random.Next(4, 10);
                            break;
                        default:
                            bigScore = random.Next(1, 5);
                            break;
                    }
                    if (isClub1Lose)
                    {
                        smallScore = bigScore * clubValue1 / clubValue2;
                        if (smallScore < 0)
                        {
                            smallScore = 0;
                        }
                        if (smallScore < bigScore)
                        {
                            if (club1.LoseTimes.HasValue)
                            {
                                club1.LoseTimes = club1.LoseTimes.Value + 1;
                            }
                            else
                            {
                                club1.LoseTimes = 1;
                            }
                            if (club2.WinTimes.HasValue)
                            {
                                club2.WinTimes = club2.WinTimes.Value + 1;
                            }
                            else
                            {
                                club2.WinTimes = 1;
                            }
                            cGame1.Ranking = 2;
                            cGame1.Score = smallScore;
                            cGame2.Ranking = 1;
                            cGame2.Score = bigScore;
                            user2.Cash = Convert.ToInt32(user2.Cash + premium);
                            strResult = club2.ID.ToString();
                        }
                        else
                        {
                            cGame1.Ranking = 1;
                            cGame1.Score = smallScore;
                            cGame2.Ranking = 1;
                            cGame2.Score = bigScore;
                            user1.Cash = Convert.ToInt32(user1.Cash + premium / 2);
                            user2.Cash = Convert.ToInt32(user2.Cash + premium / 2);
                        }

                    }
                    else
                    {
                        smallScore = bigScore * clubValue2 / clubValue1;
                        if (smallScore < bigScore)
                        {
                            if (club2.LoseTimes.HasValue)
                            {
                                club2.LoseTimes = club2.LoseTimes.Value + 1;
                            }
                            else
                            {
                                club2.LoseTimes = 1;
                            }
                            if (club1.WinTimes.HasValue)
                            {
                                club1.WinTimes = club1.WinTimes.Value + 1;
                            }
                            else
                            {
                                club1.WinTimes = 1;
                            }
                            cGame1.Ranking = 1;
                            cGame1.Score = bigScore;
                            cGame2.Ranking = 2;
                            cGame2.Score = smallScore;
                            user1.Cash = Convert.ToInt32(user1.Cash + premium);
                            strResult = club1.ID.ToString();
                        }
                        else
                        {
                            cGame1.Ranking = 1;
                            cGame1.Score = smallScore;
                            cGame2.Ranking = 1;
                            cGame2.Score = bigScore;
                            user1.Cash = Convert.ToInt32(user1.Cash + premium / 2);
                            user2.Cash = Convert.ToInt32(user2.Cash + premium / 2);
                        }
                    }
                    if (club1.FJType.Value == 5)
                    {
                        bigScore = bigScore + random.Next(90, 120);
                        smallScore = smallScore + random.Next(70, 90);
                    }
                    string strScore = bigScore.ToString() + "</b>:<b>" + smallScore.ToString();
                    arrayList.Add(strResult);
                    arrayList.Add(strScore);
                    arrayList.Add(bigScore);
                    arrayList.Add(smallScore);
                    Public.State state = new Jy123.BLL.Public.State();
                    string strUserId = "," + club1.FUser.Value.ToString() + "," + club2.FUser.Value.ToString() + ",";
                    string strUsername = "," + user1.UserName + "," + user2.UserName + ",";
                    string strSClubId = "," + club1.ID.ToString() + "," + club2.ID.ToString() + ",";
                    string strClubName = "," + club1.CName.ToString() + "," + club2.CName.ToString() + ",";
                    string strRank = ",1,2,";
                    string strSScore = "," + bigScore.ToString() + "," + smallScore.ToString() + ",";
                    if (isClub1Lose)
                    {
                        strRank = ",2,1,";
                        strScore = "," + smallScore.ToString() + "," + bigScore.ToString() + ",";
                    }
                    state.CreateRaceState(strUserId, strUsername, strSClubId, strClubName, strRank, strSScore, userV, venues);
                }
                //清空参赛俱乐部使用道具以及加油捣蛋产生的附加值
                club1.LiveNess = 0;
                club1.Morale = 0;
                club1.Skill = 0;
                club1.PhysicalFitness = 0;
                club2.LiveNess = 0;
                club2.Morale = 0;
                club2.Skill = 0;
                club2.PhysicalFitness = 0;
                //计算俱乐部的比赛次数以及胜率
                club1.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
                club1.RaceTimes += 1;
                club1.Rate = club1.WinTimes.Value * 100 / club1.RaceTimes;
                club2.RaceTimes += 1;
                club2.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
                club2.Rate = club2.WinTimes.Value * 100 / club2.RaceTimes;
                //消除参赛俱乐部已经使用道具记录
                SavePropsRecord(user1);
                SavePropsRecord(user2);

                decimal income = 0;
                if (vLevel.Income.HasValue)
                {
                    income = vLevel.Income.Value;
                }
                userV.Cash = Convert.ToInt32(userV.Cash + income);
                //赛场附属设施产生的收入（未完成）
                string strWhere = string.Format("FModule = {0} AND IsUsed = 1", venues.ID.ToString());
                Public_Annexe BLLAnnexe = new Jy123.BLL.Public_Annexe();
                Annexe_Record BLLRecord = new Jy123.BLL.Annexe_Record();
                List<Model.Annexe_Record> listRecord = BLLRecord.GetModelList(strWhere);
                List<Model.Public_Annexe> listAnnexe = BLLAnnexe.GetModelList(string.Empty);
                Dictionary<int, Jy123.Model.Public_Annexe> dicAnnexe = new Dictionary<int, Jy123.Model.Public_Annexe>();
                foreach (Jy123.Model.Public_Annexe annexe in listAnnexe)
                {
                    dicAnnexe.Add(annexe.ID, annexe);
                }
                decimal moreIncome = 0;
                foreach (Model.Annexe_Record record in listRecord)
                {
                    Model.Public_Annexe cAnnexe = dicAnnexe[record.FAnnexe.Value];
                    if (cAnnexe.Earnings.HasValue)
                    {
                        moreIncome = moreIncome + cAnnexe.Earnings.Value;
                    }
                }
                userV.Cash = Convert.ToInt32(userV.Cash.Value + moreIncome);
                BLLClubGame.Add(cGame1);
                BLLClubGame.Add(cGame2);
                BLLClub.Update(club1);
                BLLClub.Update(club2);
                game.IsEnd = true;
                BLLGame.Update(game);
                venues.RaceClub = string.Empty;
                //扣除赛场消耗的耐久度
                Public_Consume BLLConsume = new Public_Consume();
                List<Model.Public_Consume> listConsume = BLLConsume.GetModelList("FJType = " + venues.FJType.Value.ToString());
                if (listConsume.Count > 0)
                {
                    Model.Public_Consume consume = listConsume[0];
                    venues.Vitality = venues.Vitality.Value - consume.RaceScore.Value;
                    if (venues.Vitality.Value < 0)
                    {
                        venues.Vitality = 0;
                    }
                }

                venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Empty);//赛场状态设置为空闲
                venues.RaceTimes += 1;
                BLLVenues.Update(venues);
                BLLUser.Update(user1);
                BLLUser.Update(user2);
                BLLUser.Update(userV);
                cM1.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
                BLLModule.Update(cM1);
                cM2.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
                BLLModule.Update(cM2);
                vM.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Empty);
                BLLModule.Update(vM);
            }
            return arrayList;
        }

        /// <summary>
        /// 计算赛车比赛结果，派发奖金，保存比赛记录
        /// </summary>
        /// <param name="venues">进行比赛的场地</param>
        /// <returns></returns>
        public ArrayList EndCarRace(Model.Venues_Main venues)
        {
            ArrayList arrayList = new ArrayList();
            User_Main BLLUser = new User_Main();
            Public_Game BLLGame = new Public_Game();
            Venues_Main BLLVenues = new Venues_Main();
            Club_Game BLLClubGame = new Club_Game();
            Club_Main BLLClub = new Club_Main();
            Public_Level BLLLevel = new Public_Level();
            Module_Main BLLModule = new Module_Main();
            string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
            List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
            if (listGame.Count > 0)
            {
                Model.Public_Level vLevel = BLLLevel.GetModel(venues.FLevel.Value);
                string[] strClubId = venues.RaceClub.Split(',');
                string strForSQL = venues.RaceClub;
                Model.Public_Game game = listGame[0];
                Model.User_Main userV = BLLUser.GetModel(venues.FUser.Value);
                Model.Module_Main vM = BLLModule.GetModel(venues.ID);
                List<Model.Club_Main> listClub = BLLClub.GetModelList("ID IN (" + strForSQL + ")");
                List<Model.Module_Main> listModule = BLLModule.GetModelList("ID IN (" + strForSQL + ")");
                List<Model.User_Main> listFriend = BLLUser.GetModelList("ID IN (SELECT FUser FROM Club_Main WHERE ID IN (" + strForSQL + "))");
                Dictionary<int, Model.User_Main> dicFriend = new Dictionary<int, Jy123.Model.User_Main>();
                List<Model.Public_Level> listLevel = BLLLevel.GetModelList(string.Empty);
                Dictionary<int, Model.Public_Level> dicLevel = new Dictionary<int, Jy123.Model.Public_Level>();
                Dictionary<int, Model.Club_Main> dicClub = new Dictionary<int, Jy123.Model.Club_Main>();
                foreach (Model.Public_Level level in listLevel)
                {
                    dicLevel.Add(level.ID, level);
                }
                foreach (Model.User_Main user in listFriend)
                {
                    dicFriend.Add(user.ID, user);
                }

                //产生比赛结果，生成比赛结果记录
                decimal premium = 0;
                if (vLevel.Premium.HasValue)
                {
                    premium = vLevel.Premium.Value;
                }
                ArrayList rankArray = new ArrayList();
                string strSClubId = ",";
                string strClubName = ",";
                foreach (Model.Club_Main club in listClub)
                {
                    club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
                    club.RaceTimes += 1;
                    //清空参赛俱乐部使用道具以及加油捣蛋产生的附加值
                    club.LiveNess = 0;
                    club.Morale = 0;
                    club.Skill = 0;
                    club.PhysicalFitness = 0;
                    BLLClub.Update(club);
                    Model.Public_Level cLevel = dicLevel[club.FLevel.Value];
                    int clubValue = Calculate(cLevel, club);
                    ClubRank rank = new ClubRank();
                    rank.ClubValue = clubValue;
                    rank.ID = club.ID;
                    rank.ClubName = club.CName;
                    rank.Cost = Convert.ToInt32(vLevel.Cost.Value);
                    rankArray.Add(rank);
                    dicClub.Add(club.ID, club);
                    strSClubId += club.ID.ToString() + ",";
                    strClubName += club.CName + ",";
                }
                string strUserId = ",";
                string strUsername = ",";
                string strRank = ",";
                rankArray.Sort((IComparer)new CompareClub());
                int rCount = rankArray.Count;
                BLL.Scale BLLScale = new Scale();
                Model.Scale scale = BLLScale.GetModel(rCount - 1);
                string[] strScale = scale.SScale.Split(',');
                for (int i = 0; i < rCount; i++)
                {
                    ClubRank cRank = (ClubRank)rankArray[i];
                    Model.Club_Main cClub = dicClub[cRank.ID];
                    Model.Club_Game cGame = new Jy123.Model.Club_Game();
                    cGame.FVenues = venues.ID;
                    cGame.FClub = cClub.ID;
                    cGame.ClubName = cClub.CName;
                    cGame.FGame = game.ID;
                    cGame.Ranking = i + 1;
                    BLLClubGame.Add(cGame);
                    Model.User_Main user = dicFriend[cClub.FUser.Value];
                    SavePropsRecord(user);//消除参赛俱乐部已经使用道具记录
                    decimal dScale = decimal.Parse(strScale[i]);
                    int cPrelium = Convert.ToInt32(premium * rCount * dScale);
                    cRank.Prelium = cPrelium;
                    arrayList.Add(cRank);
                    user.Cash = user.Cash.Value + cPrelium;
                    BLLUser.Update(user);
                    strUserId += user.ID.ToString() + ",";
                    strUsername += user.UserName + ",";
                    strRank += (i + 1).ToString() + ",";
                }

                foreach (Model.Module_Main module in listModule)
                {
                    module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);
                    BLLModule.Update(module);
                }
                Public.State state = new Jy123.BLL.Public.State();

                state.CreateRaceState(strUserId, strUsername, strSClubId, strClubName, strRank, strRank, userV, venues);

                decimal income = 0;
                if (vLevel.Income.HasValue)
                {
                    income = vLevel.Income.Value;
                }
                userV.Cash = Convert.ToInt32(userV.Cash + income);
                //赛场附属设施产生的收入
                string strWhere = string.Format("FModule = {0} AND IsUsed = 1", venues.ID.ToString());
                Public_Annexe BLLAnnexe = new Jy123.BLL.Public_Annexe();
                Annexe_Record BLLRecord = new Jy123.BLL.Annexe_Record();
                List<Model.Annexe_Record> listRecord = BLLRecord.GetModelList(strWhere);
                List<Model.Public_Annexe> listAnnexe = BLLAnnexe.GetModelList(string.Empty);
                Dictionary<int, Jy123.Model.Public_Annexe> dicAnnexe = new Dictionary<int, Jy123.Model.Public_Annexe>();
                foreach (Jy123.Model.Public_Annexe annexe in listAnnexe)
                {
                    dicAnnexe.Add(annexe.ID, annexe);
                }
                decimal moreIncome = 0;
                foreach (Model.Annexe_Record record in listRecord)
                {
                    Model.Public_Annexe cAnnexe = dicAnnexe[record.FAnnexe.Value];
                    if (cAnnexe.Earnings.HasValue)
                    {
                        moreIncome = moreIncome + cAnnexe.Earnings.Value;
                    }
                }
                userV.Cash = Convert.ToInt32(userV.Cash.Value + moreIncome);

                game.IsEnd = true;
                BLLGame.Update(game);
                venues.RaceClub = string.Empty;
                //扣除赛场消耗的耐久度
                Public_Consume BLLConsume = new Public_Consume();
                List<Model.Public_Consume> listConsume = BLLConsume.GetModelList("FJType = " + venues.FJType.Value.ToString());
                if (listConsume.Count > 0)
                {
                    Model.Public_Consume consume = listConsume[0];
                    venues.Vitality = venues.Vitality.Value - consume.RaceScore.Value;
                    if (venues.Vitality.Value < 0)
                    {
                        venues.Vitality = 0;
                    }
                }

                venues.VStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Empty);//赛场状态设置为空闲
                venues.RaceTimes += 1;
                BLLVenues.Update(venues);

                BLLUser.Update(userV);
                vM.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Empty);
                BLLModule.Update(vM);
            }
            return arrayList;
        }

        private int Calculate(Model.Public_Level level, Model.Club_Main club)
        {
            BLL.Club_StarRecord BLLCRecord = new Club_StarRecord();
            BLL.Public_Star BLLStar = new Public_Star();
            string strWhere = string.Format("FClub = {0}", club.ID.ToString());
            List<Model.Club_StarRecord> listAllRecord = BLLCRecord.GetModelList(strWhere);
            List<Model.Public_Star> listStar = BLLStar.GetModelList(string.Empty);
            Dictionary<int, Model.Club_StarRecord> dicCRecord = new Dictionary<int, Jy123.Model.Club_StarRecord>();
            Dictionary<int, Model.Public_Star> dicStar = new Dictionary<int, Jy123.Model.Public_Star>();
            foreach (Model.Club_StarRecord record in listAllRecord)
            {
                dicCRecord.Add(record.ID, record);
            }
            foreach (Model.Public_Star star in listStar)
            {
                dicStar.Add(star.ID, star);
            }
            string[] formation = club.Formation.Split(',');
            int resultValue = 0;
            int starValue = 0;
            //计算所有球星教练的附加值
            for (int i = 0; i < formation.Length; i++)
            {
                if (!string.IsNullOrEmpty(formation[i]))
                {
                    int cRId = int.Parse(formation[i]);
                    Model.Club_StarRecord cRecord = dicCRecord[cRId];
                    switch (cRecord.SType.Value)
                    {
                        case 1:
                        case 2:
                            Model.Public_Star cStar = dicStar[cRecord.FStar.Value];
                            if (cStar.Liveness.HasValue)
                            {
                                starValue = starValue + cStar.Liveness.Value;
                            }
                            if (cStar.Moral.HasValue)
                            {
                                starValue = starValue + cStar.Moral.Value;
                            }
                            if (cStar.PhysicalFitness.HasValue)
                            {
                                starValue = starValue + cStar.PhysicalFitness.Value;
                            }
                            if (cStar.Skill.HasValue)
                            {
                                starValue = starValue + cStar.Skill.Value;
                            }
                            break;
                        case 3:
                            break;
                    }
                }
            }
            resultValue = resultValue + starValue / 10;
            //计算当前等级的俱乐部的基础值
            int clubValue = 0;
            if (level.Liveness.HasValue)
            {
                clubValue = clubValue + level.Liveness.Value;
            }
            if (level.Moral.HasValue)
            {
                clubValue = clubValue + level.Moral.Value;
            }
            if (level.PhysicalFitness.HasValue)
            {
                clubValue = clubValue + level.PhysicalFitness.Value;
            }
            if (level.Skill.HasValue)
            {
                clubValue = clubValue + level.Skill.Value;
            }
            resultValue = resultValue + clubValue * 3 / 10;
            //计算道具和加油捣蛋的值
            int propsValue = 0;
            if (club.LiveNess.HasValue)
            {
                propsValue = propsValue + club.LiveNess.Value;
            }
            if (club.Morale.HasValue)
            {
                propsValue = propsValue + club.Morale.Value;
            }
            if (club.PhysicalFitness.HasValue)
            {
                propsValue = propsValue + club.PhysicalFitness.Value;
            }
            if (club.Skill.HasValue)
            {
                propsValue = propsValue + club.Skill.Value;
            }
            resultValue = resultValue + propsValue * 3 / 10;
            //计算随机数值
            Random random = new Random();
            int randomValue = 0;
            int randomNumber = random.Next(-5, 5);
            randomValue = randomNumber * 50;
            resultValue = resultValue + randomValue * 3 / 10;
            return resultValue;
        }

        private void SavePropsRecord(Model.User_Main user)
        {
            string strPRecord = string.Format("FUser = {0} AND IsUsed = 1", user.ID.ToString());
            Club_PropsRecord BLLPRecord = new Club_PropsRecord();
            List<Model.Club_PropsRecord> listPRecord = BLLPRecord.GetModelList(strPRecord);
            foreach (Model.Club_PropsRecord record in listPRecord)
            {
                int quantity = record.Quantity.Value - 1;
                if (quantity > 0)
                {
                    record.Quantity = quantity;
                    BLLPRecord.Update(record);
                }
                else
                {
                    BLLPRecord.Delete(record.ID);
                }

            }
        }

        /// <summary>
        /// 获取俱乐部进行比赛的场地
        /// </summary>
        /// <param name="clubId">俱乐部Id</param>
        /// <returns>赛场Id</returns>
        public int GetCurrentRaceVenues(int clubId)
        {
            int vId = 0;
            Club_Main BLLClub = new Club_Main();
            Model.Club_Main club = BLLClub.GetModel(clubId);
            Venues.VModule BLLVModule = new Jy123.BLL.Venues.VModule();
            List<Jy123.Model.Venues_Main> listVenues = BLLVModule.FriendsVenues(club.FUser.Value, club.FJType.Value - 1, true);
            foreach (Jy123.Model.Venues_Main venues in listVenues)
            {
                if (!string.IsNullOrEmpty(venues.RaceClub))
                {
                    string[] strList = venues.RaceClub.Split(',');
                    if (IsInList(strList, clubId))
                    {
                        vId = venues.ID;
                        return vId;
                    }
                }

            }
            return vId;
        }
    }
}
